﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using TransactionServer.General_Classes;
using System.ComponentModel;
using Microsoft.VisualBasic.Activities;

namespace TransactionServer.CRM4Activities
{

    [Designer(typeof(TransactionServer.ActivityDesign.CRMActivities.CRMGetEntitiesByFields))]
    public sealed class CRM4GetEntitiesByFields : CodeActivity
    {
        // Define an activity input argument of type string
        public InArgument<Context> Context { get; set; }
        public InArgument<String> Connection { get; set; }
        public InArgument<String> Entity { get; set; }
        public InArgument<String[]> AttributesToReturn { get; set; }
        public InArgument<String[]> AttributesToFilter { get; set; }
        public InArgument<Object[]> Values { get; set; }

        public OutArgument<List<Entity>> Entities { get; set; }

        public CRM4GetEntitiesByFields()
        {
            VisualBasicValue<Context> vbArgument = new VisualBasicValue<Context>(Constants.CONTEXT_NAME);
            this.Context = InArgument<Context>.FromExpression(vbArgument);
        }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            Context con = context.GetValue(this.Context);
            String[] attributesToReturn = context.GetValue(this.AttributesToReturn);
            String[] attributesToFilter = context.GetValue(this.AttributesToFilter);
            Object[] values = context.GetValue(this.Values);
            string entity = context.GetValue(this.Entity);
            string connection = context.GetValue(this.Connection);

            var filter = new Filter();

            if (attributesToReturn != null)
                attributesToReturn.ToList().ForEach(attribute => filter.attributes.Add(new CAttribute(attribute)));

            if (attributesToFilter != null && values != null)
            {
                if (attributesToFilter.Length != values.Length)
                {
                    throw new Exception("Number of attributes to filter and values do not mach!");
                }
                for (int i = 0; i < attributesToFilter.Length; i++)
                {
                    filter.conditions.Add(new CCondition(attributesToFilter[i], "=", values[i].ToString()));
                }
            }

            filter.connection = connection;
            filter.entity = entity;

            CRM4Connector conn = (CRM4Connector)con.Connector[connection];

            context.SetValue(this.Entities, conn.getObjects(filter));
        }
    }
}
